/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jxtafileshare;

import net.jxta.document.MimeMediaType;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.Message.ElementIterator;
import net.jxta.endpoint.MessageElement;
import net.jxta.endpoint.WireFormatMessage;
import net.jxta.endpoint.WireFormatMessageFactory;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.InputPipe;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.pipe.PipeService;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.CountingOutputStream;
import net.jxta.util.DevNullOutputStream;

import java.io.*;
import java.io.IOException;
import java.util.Date;
/**
 *
 * @author Danny
 */
public class ShareServer extends Thread implements PipeMsgListener {
    private PeerGroup peerGroup = null;
    private transient NetworkManager manager;
    private PipeService pipeService;
    private PipeAdvertisement pipeAdv = null;
    private InputPipe inputPipe = null;
    private String fileName;

    public ShareServer(PeerGroup group, PipeAdvertisement pipeAdv,
            NetworkManager manager, String fileName) {
        peerGroup = group;
        this.manager = manager;
        this.pipeAdv = pipeAdv;
        this.fileName = fileName;

        pipeService = peerGroup.getPipeService();
    }

    public static void printMessageStats(Message msg, boolean verbose) {
        try {
            CountingOutputStream cnt;
            ElementIterator it = msg.getMessageElements();
            System.out.println("------------------Begin Message----------------");
            WireFormatMessage serialed  = WireFormatMessageFactory.toWire(msg,
                    new MimeMediaType("application/x-jxta-msg"), null);
            System.out.println("Message Size: " + serialed.getByteLength());
            while(it.hasNext()) {
                MessageElement el = it.next();
                String eName = el.getElementName();
                cnt = new CountingOutputStream(new DevNullOutputStream());
                el.sendToStream(cnt);
                long size = cnt.getBytesWritten();
                System.out.println("Element " + eName + " : " + size);
                if(verbose) {
                    System.out.println("[" + el + "]");
                }
            }
            System.out.println("-------------------End Message-----------------");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            System.out.println("Creating input pipe");

            inputPipe = pipeService.createInputPipe(pipeAdv, this);
        } catch(IOException io) {
            io.printStackTrace();
            return;
        }
        if(inputPipe == null) {
            System.out.println("Cannot open InputPipe");
            System.exit(-1);
        }
        System.out.println("Waiting for msgs on input pipe");
    }

    public void finish() {
        inputPipe.close();
    }

    public void pipeMsgEvent(PipeMsgEvent event) {
        Message msg;
        try {
            msg = event.getMessage();
            if(msg == null) {
                System.out.println("Received an empty message");
                return;
            }
            printMessageStats(msg, true);
        } catch(Exception e) {
            e.printStackTrace();
            return;
        }

        Message.ElementIterator en = msg.getMessageElements();
        if(!en.hasNext()) {
            return;
        }

        MessageElement msgElement = msg.getMessageElement(null, ShareClient.MESSAGE_NAME_SPACE);

        if(msgElement.toString() == null) {
            System.out.println("null msg received");
        } else {
            File outFile = new File(fileName);
            try {
                FileOutputStream fs = new FileOutputStream(outFile);
                ObjectOutputStream oos = new ObjectOutputStream(fs);
                oos.writeObject(msgElement);
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
            Date date = new Date(System.currentTimeMillis());
            System.out.println("Message received at: " + date.toString());
            System.out.println("Message created at: " + msgElement.toString());
        }
    }
}
